package org.http.response;

import lombok.extern.slf4j.Slf4j;
import org.http.Const;
import org.http.request.Request;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

/**
 * @author andy
 */
@Slf4j
public class HttpResponse implements Response {
    private SocketChannel socketChannel;
    private Request request;
    private CharsetEncoder encoder;
    private StringBuilder content = new StringBuilder();
    private  ResponseHeaders headers;


    public HttpResponse(Request request, SocketChannel socketChannel) {
        this.request = request;
        this.socketChannel = socketChannel;

        Charset charset = Charset.forName(Const.encoding);
        encoder = charset.newEncoder();
    }


    /**
     * 通过socketChannel将信息输出
     * @param content
     * @throws IOException
     */
    private void out(String content) throws IOException {
        CharBuffer charBuffer = CharBuffer.allocate(content.length());
        charBuffer.put(content);
        ByteBuffer bodyBuffer = encoder.encode(charBuffer);
        headers.setContentLength(bodyBuffer.capacity());
        headers.setContentType("application/json");
        ByteBuffer headerBuffer = ByteBuffer.wrap(headers.toString().getBytes());
        socketChannel.write(new ByteBuffer[]{headerBuffer, bodyBuffer});
    }

    @Override
    public void response() throws IOException {
        headers = new ResponseHeaders(200);
        headers.setCode(200);
        out(content.toString());
    }


    @Override
    public void print(String line) {
        content.append(line);
    }

    @Override
    public void println(String line) {
        content.append(line + "\r\n");
    }
}
